<?php

namespace app\admin\controller;

use app\common\business\SysDictType as SysDictTypeBus;
use app\common\lib\toCamelCase;
use app\admin\validate\SysDictType as SysDictTypeValidate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysDictType extends AuthBase
{
    //获取字典类型列表查询条件
    public function dictTypeListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->get('pageNum', 1);
        $limit = $this->request->get('pageSize', 10);
        $dictName = $this->request->get('dictName',"");
        $dictType = $this->request->get('dictType',"");
        $status = $this->request->get("status","");
        $params = $this->request->get('params',"");
        if($dictName){
            $where[] = ['dict_name', 'like', '%'.$dictName.'%'];
        }
        if($dictType){
            $where[] = ['dict_type', 'like', '%'.$dictType.'%'];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        if($params){
            $where[] = ['create_time',">=",$params['beginTime']." 00:00:00"];
            $where[] = ['create_time',"<=",$params['endTime']." 23:59:59"];
        }
        $data = [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
        ];
        return $data;
    }
    //字典类型列表
    public function dictTypeList(){
        $searchData = $this->dictTypeListSearch();
        try {
            $dictTypeData = (new SysDictTypeBus())->getNormalDictType($searchData['where'],'*',$searchData['limit'],$searchData['page']);
            $dictTypeData = (new toCamelCase())->toCamelCaseArray($dictTypeData);
        }catch (\Exception $e){
            $dictTypeData = [];
        }
        return show(config("status.success"),"字典类型列表",$dictTypeData);
    }

    //字典类型添加
    public function dictTypeAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = [
            'dict_name'=>$allParams['dictName'],
            'dict_type'=>$allParams['dictType'],
            'remark'=>$allParams['remark']??null,
            'status'=>$allParams['status'],
        ];
        $validate = new SysDictTypeValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            $result = (new SysDictTypeBus())->addDictType($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"新增成功",$result);
    }

    //字典类型修改
    public function dictTypeEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        try {
            $result = (new SysDictTypeBus())->updateById($data['dict_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改成功",$result);
    }

    //删除字典类型
    public function dictTypeDel(){
        $type = $this->request->param("type","","trim");
        if(empty($type)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SysDictTypeBus())->DeldictTypeIds($type);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //字典类型详情
    public function dictTypeDetails(){
        $type = $this->request->param("type","","trim");
        if(empty($type)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $dictTypeData = (new SysDictTypeBus())->getDictTypeById($type);
            $dictTypeData = (new toCamelCase())->toCamelCaseArray($dictTypeData);
        }catch (\Exception $e){
            $dictTypeData = [];
        }
        return show(config("status.success"),"字典类型详情",$dictTypeData);
    }

    //导出字典类型数据
    public function exportDictType(){
        $searchData = $this->dictTypeListSearch();
        $postCount = (new SysDictTypeBus())->getNormalDictTypeCount($searchData['where']);
        $dictTypeData = (new SysDictTypeBus())->getNormalDictType($searchData['where'],'*',$postCount,$searchData['page']);

        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:F1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '字典类型数据');
        // 设置表头
        $header = ['字典编号', '字典名称', '字典类型', '状态', '备注','创建时间'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(18);
        }
        // 填充数据
        $row = 3;
        foreach ($dictTypeData['data'] as $post) {
            $post['status'] = $post['status'] === '0' ? "正常" : "停用";
            $sheet->setCellValue('A' . $row, $post['dict_id']);
            $sheet->setCellValue('B' . $row, $post['dict_name']);
            $sheet->setCellValue('C' . $row, $post['dict_type']);
            $sheet->setCellValue('D' . $row, $post['status']);
            $sheet->setCellValue('E' . $row, $post['remark']);
            $sheet->setCellValue('F' . $row, $post['create_time']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:F2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:F2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':F' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':F' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="post.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }

    //刷新缓存
    public function clearCache($prefix = ''){
        /*if (empty($prefix)) {
            // 如果没有指定前缀，则可能需要根据实际情况决定是否允许清空所有缓存
            // 这里为了安全起见，我们直接返回错误或仅允许清空特定前缀的缓存
            return json(['error' => '必须指定缓存前缀']);
        }*/

        // 使用 Cache 类的 clear 方法清空指定前缀的缓存
        // 注意：这里假设你的缓存驱动支持前缀功能，并非所有缓存驱动都原生支持前缀
        // 如果你的缓存驱动不支持前缀，你可能需要遍历并删除所有符合条件的键
        //$result = Cache::clear();
        $result = true;
        // 假设 clear 方法成功执行返回 true，否则返回 false
        // 注意：实际中 clear 方法的行为可能因缓存驱动而异，这里仅为示例
        if ($result) {
            return show(config("status.success"),"缓存刷新成功");
        } else {
            return show(config("status.error"),"缓存刷新失败");
        }
    }

    //获取字典选择框列表
    public function optionselect(){
        $searchData = $this->dictTypeListSearch();
        try {
            $postCount = (new SysDictTypeBus())->getNormalDictTypeCount($searchData['where']);
            $dictTypeData = (new SysDictTypeBus())->getNormalDictType($searchData['where'],'*',$postCount,$searchData['page']);
            $dictTypeData = (new toCamelCase())->toCamelCaseArray($dictTypeData);
        }catch (\Exception $e){
            $dictTypeData = [];
        }
        return show(config("status.success"),"字典类型列表",$dictTypeData);
    }
}
